import copy
import random


class Crossover:
    def run(self, genetic_prompt1, genetic_prompt2):
        diff_gene = []
        for i, gene in enumerate(genetic_prompt1.chunks):
            if i >= len(genetic_prompt2.chunks) or gene != genetic_prompt2.chunks[i]:
                diff_gene.append(i)

        if len(diff_gene) > 0:
            index = random.choice(diff_gene)
        elif len(genetic_prompt1.chunks) > len(genetic_prompt2.chunks):
            index = len(genetic_prompt2.chunks)
        elif len(genetic_prompt1.chunks) < len(genetic_prompt2.chunks):
            index = len(genetic_prompt1.chunks)
        else:
            return genetic_prompt1, genetic_prompt2

        new_genetic_prompt1 = copy.deepcopy(genetic_prompt1)
        new_genetic_prompt2 = copy.deepcopy(genetic_prompt2)

        if index >= len(genetic_prompt2.chunks):
            new_genetic_prompt1.chunks[index] = ""
            new_genetic_prompt2.chunks.append(genetic_prompt1.chunks[index])
            new_genetic_prompt2.sequence.append(len(genetic_prompt2.chunks))

        elif index >= len(genetic_prompt1.chunks):
            new_genetic_prompt2.chunks[index] = ""
            new_genetic_prompt1.chunks.append(genetic_prompt2.chunks[index])
            new_genetic_prompt1.sequence.append(len(genetic_prompt1.chunks))

        else:
            new_genetic_prompt1.chunks[index], new_genetic_prompt2.chunks[index] = new_genetic_prompt2.chunks[index], new_genetic_prompt1.chunks[index]

        new_genetic_prompt1.clear_scores()
        new_genetic_prompt2.clear_scores()
        return new_genetic_prompt1, new_genetic_prompt2
